package com.lv.service.dialog

import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.text.TextUtils
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.lv.common.imp.OnPositionTListener
import com.lv.common.utils.*
import com.lv.service.R
import com.lxj.xpopup.core.CenterPopupView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class ShowCodePopupView(
    private val mContext: Context,
    private val mTitle: String,
    private val mLogo: String,
    private val mPositionTListener: OnPositionTListener<String>? = null
) :
    CenterPopupView(mContext) {
    private var mLogoBitmap: Bitmap? = null
    private var mCodeBitmap: Bitmap? = null
    override fun getImplLayoutId(): Int {
        return R.layout.show_code_popup
    }

    override fun onCreate() {
        super.onCreate()
        val ivCode = findViewById<ImageView>(R.id.iv_code)
        val ivClose = findViewById<ImageView>(R.id.iv_close)
        val clContainer = findViewById<ConstraintLayout>(R.id.cl_container)
//        val deCodeUrl = URLEncoder.encodeWithUtf8(mTitle)
        CoroutineScope(Dispatchers.Default).launch {
            mLogoBitmap = getNotificationBitmapFromCache(mLogo)
            mCodeBitmap = getBitmap(mTitle)
            setBitmap(ivCode)
        }
        clContainer.setOnLongClickListener {
            checkPermissions()
            return@setOnLongClickListener false
        }
        ivClose.setOnClickListener { dismiss() }


        initView()
        initEvnet()
    }

    private fun checkPermissions() {
        val permissions = mutableListOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
        )
        PermissionXUtils.checkPermissBefore(
            context as FragmentActivity, permissions, "您需要授予存储权限才能保存二维码到相册",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        startSave()
                    }
                }

                override fun fotPermsission() {

                }
            },
        )
    }

    private fun startSave() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            SaveImageUtils.saveImageToGallery2(mContext, mCodeBitmap) {
                showToast("图片保存成功,请到相册查找")
            }
        } else {
            SaveImageUtils.saveImageToPhotos(mContext, mCodeBitmap) {
                showToast("图片保存成功,请到相册查找")
            }
        }
    }

    private fun initView() {

//        tvTitle?.text = mTitle


    }

    private fun initEvnet() {


    }

    private suspend fun getBitmap(deCodeUrl: String): Bitmap {
        return CodeUtil.createImage(deCodeUrl, 320, 320, mLogoBitmap)
    }

    private suspend fun setBitmap(imageView: ImageView) {
        (context as Activity).runOnUiThread {
            imageView.setImageBitmap(mCodeBitmap)
        }
    }

    private suspend fun getNotificationBitmapFromCache(url: String?): Bitmap? {
        if (TextUtils.isEmpty(url)) {
            return null
        }
        val resultBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565)
        resultBitmap.eraseColor(Color.WHITE)
        // 使用空白图片生成canvas
        val canvas = Canvas(resultBitmap)
        //第一步先把原图全部画上去
        //源图-尺寸
        val srcRect = Rect(0, 0, 100, 100)
        //目标-位置
        val dstRect = Rect(0, 0, 100, 100)
        canvas.drawBitmap(resultBitmap, srcRect, dstRect, null)
        var cachedBitmap: Bitmap? = null
        try {
            cachedBitmap = Glide.with(mContext).asBitmap().load(url).apply(
                RequestOptions().centerCrop().override(100, 100)
            ).submit()[500, TimeUnit.MILLISECONDS] // 最大等待200ms
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return cachedBitmap
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()


    }

}